import { Injectable, ExecutionContext, UnauthorizedException, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class LoggingInterceptor {
  // 定义不需要拦截的路径列表
  private readonly skipPaths = ['/auth/login', '/auth/signup'];

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    console.log('Before...');

    const request = context.switchToHttp().getRequest();
    const url = request.url; // 获取请求路径

    // 如果是需要跳过的路径，则直接放行
    if (this.skipPaths.some((path) => url.endsWith(path))) {
      console.log(`Skipping token check for path: ${url}`);
      const now = Date.now();
      return next.handle().pipe(
        tap(() => console.log(`After... ${Date.now() - now}ms`)),
      );
    }

    // 检查 token 是否存在
    const token = request.headers['authorization'];
    if (!token) {
      throw new UnauthorizedException('未提供有效的身份验证令牌');
    }

    // 简单的 token 验证逻辑（可以根据实际需求替换）
    if (token !== 'valid-token') {
      throw new UnauthorizedException('身份验证令牌无效');
    }

    const now = Date.now();

    return next.handle().pipe(
      tap(() => console.log(`After... ${Date.now() - now}ms`)),
    );
  }
}